package com.coldlz.mmp.ssl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.crypto.KeyUtil;
import org.bouncycastle.cert.X509CertificateHolder;
import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter;

import java.io.File;
import java.io.IOException;
import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.stream.Collectors;

public class Util {

    static final File SSL_DIR = new File("data/ssl");


    public static List<String> splitString(String input) {
        int length = 64;
        List<String> result = new ArrayList<>();
        for (int i = 0; i < input.length(); i += length) {
            int end = Math.min(input.length(), i + length);
            result.add(input.substring(i, end));
        }
        return result;
    }

    public static KeyPairStr loadKeyPairStr(List<String> privateKeyLines, List<String> publicKeyLines) {
        String privateKey = privateKeyLines.stream().filter(s -> !s.isEmpty() && !s.startsWith("--")).collect(Collectors.joining());
        String publicKey = publicKeyLines.stream().filter(s -> !s.isEmpty() && !s.startsWith("--")).collect(Collectors.joining());
        return loadKeyPairStr(privateKey, publicKey);
    }

    public static KeyPairStr loadKeyPairStr(String privateKey, String publicKey) {
        PrivateKey pri = KeyUtil.generateRSAPrivateKey(Base64.getDecoder().decode(privateKey.getBytes()));
        PublicKey pub = KeyUtil.generateRSAPublicKey(Base64.getDecoder().decode(publicKey.getBytes()));

        KeyPair keyPair = new KeyPair(pub, pri);
        return new KeyPairStr(keyPair);
    }


    public static X509Certificate loadCert(List<String> certStrLines) {
        String certStr = certStrLines.stream().filter(s -> !s.isEmpty() && !s.startsWith("--")).collect(Collectors.joining());
        return loadCert(certStr);
    }

    public static X509Certificate loadCert(String certStr) {
        byte[] decode = Base64.getDecoder().decode(certStr);
        X509Certificate x509Certificate;
        try {
            X509CertificateHolder holder = new X509CertificateHolder(decode);
            x509Certificate = new JcaX509CertificateConverter().setProvider("BC").getCertificate(holder);
        } catch (IOException | CertificateException ei) {
            throw new RuntimeException(ei);
        }
        if (x509Certificate == null) {
            throw new RuntimeException("加载证书失败");
        }
        return x509Certificate;
    }

    public static File getCertFile(String namePrefix) {
        return new File(SSL_DIR, namePrefix + "-cert.crt");
    }

    static File getPublicKeyFile(String namePrefix) {
        return new File(SSL_DIR, namePrefix + "-public.key");
    }

    static File getPrivateKeyFile(String namePrefix) {
        return new File(SSL_DIR, namePrefix + "-private.key");
    }

    static void savePrivateKeyToFile(String privateKeyToFileStr, String namePrefix) {
        FileUtil.writeUtf8String(privateKeyToFileStr, Util.getPrivateKeyFile(namePrefix));
    }

    static void savePublicKeyToFile(String publicKeyToFileStr, String namePrefix) {
        FileUtil.writeUtf8String(publicKeyToFileStr, Util.getPublicKeyFile(namePrefix));
    }
}
